package blue.web.commons.service;

import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@Service
public class ExcelService {

    private final int FAILED_VALUE=-1;

    private final int FAILED_EXEEL=-4;

    private final int SUCCESS=1;

    @Autowired
    private OSSService ossService;

    public int writeData2Excel(List<Map<String, Object>> data,Map aliasHeader, String sheetName,String fileName, String bucketName){

        if(CollectionUtils.isEmpty(data) || StringUtils.isBlank(fileName)){
            return FAILED_VALUE;
        }

        try {
            ExcelWriter excelWriter=new ExcelWriter();

            if(aliasHeader!=null){
                excelWriter.setHeaderAlias(aliasHeader);
            }

            //清除无用sheet
            int count=excelWriter.getSheetCount();
            for(int i=0;i<count;i++){
                excelWriter.getWorkbook().removeSheetAt(0);
            }

            if(StringUtils.isNotBlank(sheetName)){
                excelWriter.setSheet(sheetName);
            }
            excelWriter.write(data);

            OutputStream outputStream=new ByteArrayOutputStream();

            excelWriter.getWorkbook().write(outputStream);

            InputStream in=parse(outputStream);

            boolean result= ossService.putObject(fileName,in,bucketName, ossService.getOSSClient());

            if(result){
                return SUCCESS;
            }

        }catch (Exception e){

            return FAILED_EXEEL;
        }

        return FAILED_VALUE;
    }


    public ByteArrayInputStream parse(OutputStream out) throws Exception
    {
        ByteArrayOutputStream   baos=new ByteArrayOutputStream();
        baos=(ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

}
